<template>
  <div>
    <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
      <UserSearchComponent @setUserInfo="setUserInfo" />
      <UserInfo :userInfo="userInfo" />
      <el-form-item label="省份" prop="province">
        <el-input
          v-model="form.province"
          disabled
          class="province"
          :input-style="{ width: '300px' }"
        />
      </el-form-item>
      <el-form-item
        :label="subject.title"
        prop="sgname"
        v-for="subject in primarySubjects"
        :key="subject.title"
      >
        <el-radio-group
          v-model="form.sgname"
          size="small"
          :disabled="!userPhone"
        >
          <!-- 遍历 subject.data 数组中的每个科目 -->
          <el-radio
            :value="item.id"
            border
            v-for="item in subject.data"
            :key="item.id"
          >
            {{ item.name }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        :label="subject.title"
        prop="sgname2"
        v-for="subject in secondarySubjects"
        :key="subject.title"
      >
        <el-checkbox-group
          v-model="form.sgname2"
          size="small"
          :disabled="!userPhone"
          :min="0"
          :max="form.province == '北京' || subject.number == '3' ? 3 : 2"
        >
          <!-- 遍历 subject.data 数组中的每个科目 -->
          <el-checkbox
            :value="item.id"
            border
            v-for="item in subject.data"
            :key="item.id"
            :disabled="!userPhone"
          >
            {{ item.name }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="分数" prop="score">
        <el-input-number
          v-model="form.score"
          :min="100"
          :max="750"
          :disabled="!userPhone"
        />
        <div class="titleHeader" style="margin-left: 10px">
          <el-icon>
            <InfoFilled />
          </el-icon>
          分数区间 100-750
        </div>
      </el-form-item>
      <el-form-item label="位次" prop="section">
        <el-input-number
          v-model="form.section"
          :min="1"
          :disabled="!userPhone"
        />
      </el-form-item>
      <el-form-item label="">
        <div style="color: red">
          修改任何一项信息，都可能会导致已填的志愿表失效！请谨慎操作！如有疑问，请联系客服。
        </div>
      </el-form-item>
      <el-form-item label="申请原因" prop="remark">
        <div style="display: flex; flex-direction: column">
          <el-input
            v-model="form.remark"
            type="textarea"
            :maxlength="100"
            :show-word-limit="true"
            :input-style="{ height: '100px', width: '300px' }"
          />
        </div>
      </el-form-item>
      <el-form-item label="相关凭证" prop="auditImage">
        <el-upload
          class="upload-demo"
          ref="uploadRef"
          :limit="1"
          accept=".jpg,.png"
          :headers="upload.headers"
          :http-request="customUploadRequest"
          :show-file-list="false"
        >
          <!-- 如果有图片则显示上传的图片，否则显示上传图标 -->
          <div v-if="form.auditImage" class="avatar-wrapper">
            <img :src="form.auditImage" class="avatar" alt="图片" />
            <!-- 替换按钮（可选） -->
            <div class="replace-btn" @click.stop="handleRemove">替换图片</div>
          </div>
          <div v-else class="avatar-uploader">
            <el-icon class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </div>
        </el-upload>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          class="primary"
          @click="submitForm(formRef)"
          :disabled="!form.orderStudent"
          >提交</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="tsx" setup>
import { reactive, ref } from 'vue';
import type { FormInstance, FormRules } from 'element-plus';
import { ElMessage, UploadInstance } from 'element-plus'; // 确保以这种方式导入
import common from '@/modules';
import { getToken } from '@/utils/auth';
import { uploadFile } from '@/api/serviceCenter';
import UserSearchComponent from '@/components/UserSearchComponent/index.vue';
import UserInfo from '@/components/UserInfo/index.vue';
import { get } from 'lodash';
const { getSubjectOptions } = common;
const emit = defineEmits(['submit']);
// 用户信息
const userInfo: { [key: string]: any } = reactive({
  当前成绩: '-分 - 位',
  历史变更次数: '次',
});
// 根据用户手机进行禁用判断
const userPhone = ref(null);
// 当前省份选科类型
const xk_type = ref('');
// 单选科目和再选科目，使用 ref 创建响应式数组
const primarySubjects = ref<Subject[]>([]);
const secondarySubjects = ref<Subject[]>([]);

// 定义上传请求参数的类型
interface UploadRequestOptions {
  file: File; // 文件类型
  onSuccess: (response: any) => void; // 上传成功回调函数
  onError: (error: any) => void; // 上传失败回调函数
  onProgress: (event: { percent: number }) => void; // 上传进度回调函数
}
// 上传参数
const upload = reactive({
  // 上传二维码弹窗变量
  open: false,
  // 弹出层标题
  title: '上传图片',
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Token: getToken() },
  // 上传的地址
  url: '/dev-api/api/index/imageUpload',
  imgurl: '',
  // 是否禁用上传
  disabled: true,
});
const formRef = ref<FormInstance>();
const uploadRef = ref<UploadInstance | null>(null);
// 表单数据
const form = reactive({
  province: '暂无信息',
  sgname: '',
  sgname2: [],
  auditImage: '',
  score: 100,
  section: 1,
  remark: '',
  orderStudent: '',
  num: 100,
});

// 表单验证
const rules = reactive<FormRules>({
  score: [
    {
      required: true,
      trigger: 'blur',
      message: '请填写分数',
    },
  ],
  sgname: [
    {
      required: true,
      trigger: 'change',
      message: '请选择科目',
    },
  ],
  sgname2: [
    {
      required: true,
      message: '请选择再选科目',
      trigger: 'change',
    },
  ],
  remark: [
    {
      required: true,
      message: '请填写申请原因',
      trigger: 'change',
    },
  ],
});

// 表单提交
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid) => {
    if (valid) {
      const params = {
        // 修改前的成绩
        aftarScore: userInfo['当前成绩'],
        // 历史变更次数
        aftarGkb_score_num: userInfo['历史变更次数'],
      };
      emit('submit', { ...form, ...params });
    }
  });
};

// 删除/替换图片
const handleRemove = () => {
  form.auditImage = ''; // 清空图片 URL，允许用户上传新的图片
  uploadRef.value?.clearFiles(); // 清空文件列表，重置上传状态
};
// 自定义上传请求的逻辑
const customUploadRequest = async ({
  file,
  onSuccess,
  onError,
  onProgress,
}: UploadRequestOptions) => {
  // 文件大小限制为 5MB
  const maxFileSize = 5 * 1024 * 1024; // 5MB

  // 判断文件大小是否超过 5MB
  if (file.size > maxFileSize) {
    ElMessage({
      message: '文件大小不能超过 5MB',
      type: 'error',
    });
    return; // 阻止上传
  }

  // 调用封装的 uploadFile 函数来处理上传逻辑
  uploadFile(
    file,
    upload.url, // 上传的 URL
    upload.headers, // 自定义请求头
    (progressEvent: any) => {
      // 进度回调
      onProgress({ percent: Number(progressEvent.percent) }); // 进度回调
    },
    (response: any) => {
      onSuccess(response); // 上传成功的回调
      form.auditImage = response.data.url; // 假设返回的图片 URL 存储在 response.data.url
    },
    (error: any) => {
      onError(error); // 上传失败的回调
    }
  );
};
// 定义科目项接口
interface SubjectItem {
  name: string; // 科目名称
  id: string; // 科目代码
  province?: string; // 科目代码
}

// 定义科目接口
interface Subject {
  type: string; // "1" 或 "2" 表示科目类型
  title: string; // 科目标题
  prop?: string; // 科目标题
  data: SubjectItem[]; // 科目内容，应该是数组
  number?: string; // 可选的 "number" 字段，只在 type 为 "2" 时存在
  province?: string;
}

// 获取科目和再选科目列表
const processSubjects = (
  xk_type: string
): { primarySubjects: Subject[]; secondarySubjects: Subject[] } => {
  const subArr: Subject[] = getSubjectOptions(xk_type);

  // 初始化两个空数组
  const primarySubjects: Subject[] = []; // type为"1"的科目列表
  const secondarySubjects: Subject[] = []; // type为"2"的再选科目列表

  // 遍历数据，根据type进行分类
  subArr.forEach((subject) => {
    if (subject.type === '1') {
      primarySubjects.push(subject); // 普通数组，直接 push
    } else {
      secondarySubjects.push(subject); // 普通数组，直接 push
    }
  });

  return { primarySubjects, secondarySubjects };
};

// 设置用户信息
const setUserInfo = (val: any) => {
  form.sgname = '';
  form.sgname2 = [];
  secondarySubjects.value = [];
  primarySubjects.value = [];
  const params = {
    当前成绩:
      get(val, 'score', '') +
      '-分' +
      get(val, 'section', '') +
      '-位' +
      '-' +
      get(val, 'sgname', ''),
    历史变更次数: get(val, 'gkb_score_num', 0) + '次',
  };

  // 使用安全获取
  userPhone.value = get(val, 'phone', '');

  // 解构并处理选科类型
  const { primarySubjects: tempPrimary, secondarySubjects: tempSecondary } =
    processSubjects(get(val, 'xk_type', ''));
  // 将分类结果赋值到响应式数组中，使用 .value 访问 ref
  form.province = get(val, 'province', '');
  primarySubjects.value = tempPrimary || [];
  secondarySubjects.value = tempSecondary || [];
  xk_type.value = get(val, 'xk_type', '');

  // 安全合并用户信息
  Object.assign(userInfo, params);

  // 设置表单的学生手机号
  form.orderStudent = get(val, 'phone', '');
};
</script>

<style lang="scss" scoped>
.replace-btn {
  position: absolute;
  bottom: 0;
  color: #fff;
  background: rgba(0, 0, 0, 0.6);
  width: 100%;
  left: 0;
  text-align: center;
  cursor: pointer;
}

.province {
  :deep(.el-input__wrapper) {
    box-shadow: none;
    background: unset;
    color: #666 !important;
    font-size: 14px;
  }

  :deep(.el-input__inner) {
    color: #666 !important;
    font-size: 14px;
    -webkit-text-fill-color: unset;
    cursor: unset;
  }
}

.primary {
  width: 170px;
  color: #fff;
  background-color: #165dff;
  border-color: #165dff;
  height: 40px;
}

.primary:hover {
  opacity: 0.8;
}
</style>
